package com.luccesit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.luccesit.entity.Publish;
import com.luccesit.util.db.DBHelp;
import com.luccesit.util.db.Page;
import com.luccesit.util.db.RowMapper;


public class PublishDao {

	private DBHelp<Publish> db = new DBHelp<Publish>();
	
	public void save(Publish p) {
		String sql = "insert into t_publish(id,pubname,createtime) values(?,?,?)";
		db.executeSQL(sql, p.getId(),p.getPubname(),p.getCreatetime());
	}
	
	public void update(Publish p) {
		String sql = "update t_publish set pubname = ? where id = ?";
		db.executeSQL(sql, p.getPubname(),p.getId());
	}
	
	public Publish findById(String id) {
		String sql = "select id,pubname,createtime from t_publish where id = ?";
		return db.executeQueryToObject(sql, new PublishRowMapper(), id);
	}
	
	public List<Publish> findAll() {
		String sql = "select id,pubname,createtime from t_publish";
		return db.executeQueryToList(sql, new PublishRowMapper());
	}
	
	public int count() {
		String sql = "select count(*) from t_publish";
		return db.executeQueryToNumber(sql).intValue();
	}
	
	public Page<Publish> findByPage(int pageNum) {
		String sql = "select id,pubname,createtime from t_publish limit ?,?";
		Page<Publish> page = new Page<Publish>(count(),pageNum);
		page.setList(db.executeQueryToList(sql, new PublishRowMapper(),page.getStart(),page.getPageSize()));
		return page;
	}
	
	private class PublishRowMapper implements RowMapper<Publish> {

		public Publish mapRow(ResultSet rs) throws SQLException {
			Publish p = new Publish();
			p.setCreatetime(rs.getString("createtime"));
			p.setId(rs.getString("id"));
			p.setPubname(rs.getString("pubname"));
			return p;
		}
		
	}
}
